import os
import subprocess


class GPIO:
    def __init__(self, gpio: int | str):
        self.status = False
        self.gpio = int(gpio)
        self.init_gpio()

    def check_gpio_export(self):
        return os.path.exists(f"/sys/class/gpio/gpio{self.gpio}")

    def init_gpio(self):
        if not self.check_gpio_export():
            os.system(f"echo {self.gpio} > /sys/class/gpio/export")
        os.system(f"echo out > /sys/class/gpio/gpio{self.gpio}/direction")

    def open(self):
        self.status = True
        self.set_gpio_value(1)

    def close(self):
        self.status = False
        self.set_gpio_value(0)

    def get_gpio_value(self):
        result = subprocess.run(
            ["cat", f"/sys/class/gpio/gpio{self.gpio}/value"], stdout=subprocess.PIPE
        )
        return result.stdout.decode("utf-8").strip()

    def set_gpio_value(self, value):
        os.system(f"echo {value} > /sys/class/gpio/gpio{self.gpio}/value")
